#pragma once
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<unistd.h>

#define MAX_SIZE 4096
#define PATH_NAME "."
#define PROJ_ID 0x55

//利用shm实现进程间通信1.创建共享内存（获取共享内存） 2.将shm与进程挂起 3.将shm与进程取消挂起 4.回收共享内存

key_t getkey(){
    int key = ftok(PATH_NAME,PROJ_ID);
    if(key == -1){
        std::cerr<<"ftok filed"<<strerror(errno)<<std::endl;
        exit(1);
    }
    return key;
}

int getshm(key_t key,int flags){
    int shm_id  = shmget(key,MAX_SIZE,flags);
    if(shm_id == -1){
        std::cerr<<"shmget filed"<<strerror(errno)<<std::endl;
        exit(2);
    }
    return shm_id;
}

int createshm(key_t key){
    int shm_id = getshm(key,IPC_CREAT|IPC_EXCL|0600);
    return shm_id;
}

int getshm(key_t key){
    int shm_id = getshm(key,IPC_CREAT);
    return shm_id;
}

void* shmattach(int shmid){
    void* shmaddr = shmat(shmid,NULL,0);
    if((long long) shmaddr == -1){
        std::cerr<<"shmat filed"<<strerror(errno)<<std::endl;
        exit(3);
    }
    return shmaddr;
}

void shmdetach(const char* shmaddr){
    int r = shmdt(shmaddr);
    if(r == -1){
        std::cerr<<"shmdt filed"<<strerror(errno)<<std::endl;
        exit(4);
    }
}

void shmdelete(int shmid){
    int r = shmctl(shmid,IPC_RMID,NULL);
    if(r == -1){
        std::cerr<<"shmdelete filed"<<strerror(errno)<<std::endl;
        exit(5);
    }
}

